import binascii
from utils.database import Model
from utils.save import Save


class Baidu(Model, Save):
    table = "news_baidu"

    def add(self, item):
        self.do_insert({
            "title": item["title"].strip(),
            "link": item["link"].strip(),
            "link_crc32": binascii.crc32(item["link"].encode()),
            "sort": int(item["sort"]),
            "index": int(item["index"]),
            "is_new": int(item["is_new"]),
            "is_rise": int(item["is_rise"]),
            "create_time": item["update_time"],
            "update_time": item["update_time"]
        })

    def update(self, id, item):
        params = {
            "update_time": item["update_time"],
            "sort": int(item["sort"]),
            "index": int(item["index"]),
            "is_new": int(item["is_new"]),
            "is_rise": int(item["is_rise"]),
        }

        self.do_update(params, {"id": id})

    def get_tops(self, num):
        sql = "select * from $table order by update_time desc, `index` desc limit ?"
        params = (num,)

        return self.query_all(sql, params)

